/**
 * Created by Administrator on 2018/6/22.
 */




////// 基本信息 - 条形图 //////
function drawBar(id){
    var colors = ['#eb2100','#eb3600','#d0570e','#d0a00e','#34da62','#00e9db','#00c0e9','#0096f3'];
    var option = {
        tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
        grid: {
            top:'37px', left: '50px', right: '4%', bottom: '40px',
            containLabel: true
        },
        color:colors,
        backgroundColor:'#fff',
        xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01],
            splitLine:{show:false},
            axisLine:{show:false},
            axisTick:{show:false},
            axisLabel:{show:false}
        },
        yAxis: {
            type: 'category',
            axisLabel:{margin:20, textStyle:{fontSize:14, color:'#000'}},
            axisLine:{show:false},
            axisTick:{show:false},
            splitLine:{show:false},
            data: ['负面/处分', '荣誉/奖励', '工作经历', '教育程度', '党龄', '年龄',]
        },
        series: [{
            type: 'bar', barWidth:25,
            label:{ normal:{show:true, position: "right", textStyle:{color:"#000"} }},
            itemStyle:{normal:{color:function(d){ return colors[d.dataIndex]; }}},
            data: [0, 10, 17, 35, 19, 39]
        },]
    };
    var e = Init3(option , id);
    window.onresize = function () {
        $("#view1").width(($("#view0").width() - $("#baseInfo").width() - 10));
        e.resize();
    };
}

/* 雷达图 */
function drawRadar(id){
    var option = {
        title: { subText: '综合分析' }, tooltip: {},
        textStyle:{color:"#000", fontSize:14},
        //legend: { data: ['预算', '实际'] },
        radar: {
            //shape: 'circle',
            radius: "68%",
            splitArea: {show:false},
            indicator: [
                { name: '学历', max: 100},
                { name: '研究成果', max: 100},
                { name: '荣誉', max: 100},
                { name: '工作年限', max: 100},
                { name: '经历', max: 100},
                { name: '绩效', max: 100},
                { name: '群众满意度', max: 100}
            ]
        },
        series: [{
            name: '预算 vs 开销',
            type: 'radar',
            areaStyle: {normal: {}},
            //itemStyle:{normal:{ color:"#fff"}},
            label:{normal:{show:false, textStyle:{ color:"#fff"}}},
            data : [ { value : [85, 20, 50, 80, 80, 85, 100], name : '预算' }],
        }]
    };
    Init3(option, id);
}




function drawLine(id){
    var width  = $("#"+id).width();
    var height = $("#"+id).height();
    var padding = {top:60, right:70, bottom:30, left:70};
    var SVGH = height - padding.top - padding.bottom;
    var level = 14, part = 20;

    var svg = d3.select("#" + id)			//选择<body>
        .append("svg")			//在<body>中添加<svg>
        .attr("width", width)	//设定<svg>的宽度属性
        .attr("height", height);//设定<svg>的高度属性

    var xScale = d3.scaleLinear()
        .domain([1979, 2020])
        .range([0, width - padding.left - padding.right]);
    var yScale = d3.scaleLinear()
        .domain([0, level])		//定义域
        .range([SVGH, 0]);
    var yScale2 = d3.scaleLinear()
        .domain([0, level])		//定义域
        .range([SVGH, 0]);

    var xAxis = d3.axisBottom().scale(xScale).tickFormat(d3.format("")).ticks(part);	//值域;
    var yAxis = d3.axisLeft().scale(yScale).tickFormat("").ticks(level);
    var yAxis2 = d3.axisLeft().scale(yScale2).tickFormat("").ticks(level);
    var lineFunc = d3.line().x(function(d){return d.x;}).y(function(d){return d.y;});
    var disY = (height - padding.top - padding.bottom) / level;

    ////// 网格部分 //////
    function addGrid(){
        function make_x_axis() { return d3.axisBottom().scale(xScale).ticks(part); }
        function make_y_axis() { return d3.axisLeft().scale(yScale).ticks(level); }
        svg.append("g").attr("class", "grid")
            .attr("transform", "translate(" + padding.left + "," + (height - padding.bottom) + ")")
            .call(make_x_axis().tickSize(-height + padding.top + padding.bottom, 0, 0).tickFormat(""));
        svg.append("g").attr("class", "grid")
            .attr("transform", "translate(" + padding.left + "," + (padding.top) + ")")
            .call(make_y_axis().tickSize(-width + padding.left + padding.right, 0, 0).tickFormat(""))
    }

    //////// 坐标轴 ////////
    function addAxis(){
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + padding.left + "," + (height - padding.bottom) +  ")")
            .call(xAxis);
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + padding.left + "," + (padding.top) +  ")")
            .call(yAxis);
        svg.append("g")
            .attr("class","axis")
            .attr("transform","translate(" + (width - padding.left) + "," + (padding.top) +  ")")
            .call(yAxis2);
        // 坐标轴文字
        svg.append("text").text("时间轴")
            .attr("transform","translate(" + (width - padding.right + 10) + "," + (height - padding.bottom + 5) + ")");
        svg.append("text").text("职级")
            .attr("transform","translate(" + (padding.left - 30) + "," + (padding.top - 10) + ")");
        svg.append("text").text("教育")
            .attr("transform","translate(" + (width - padding.right) + "," + (padding.top - 10) + ")");
    }

    // 国家主席 国务院总理 国务院副总理
    var levelAdm = ["", "", "", "", "", "司级 [正]", "司级 [副]", "处级 [正]", "处级 [副]", "科级 [正]", "科级 [副]", "科员", "办事员", ""];
    var levelEdu = ["", "", "", "博士后", "海归博士", "博士", "硕士", "本科", "大专", "高中", "中专", "初中", "小学", ""];


    ////// 坐标轴文字 //////
    function addAxisText(){
        svg.append("g").selectAll("text").data(levelAdm).enter().append("text")
            .text(function(d){ return d; })
            .attr("transform", function(d, i){ return "translate(" + (padding.left - 12) + "," + (padding.top + disY * i + disY/2 + 8) + ")"; })
            .style("text-anchor", "end");
        svg.append("g").selectAll("text").data(levelEdu).enter().append("text")
            .text(function(d){ return d; })
            .attr("transform", function(d, i){ return "translate(" + (width - padding.right + 10) + "," + (padding.top + disY * i + disY/2 + 8) + ")"; })
            .style("text-anchor", "start");
        // 提示线
        var y = yScale2(6) + padding.top;
        svg.append("g").append("path").attr("d", lineFunc([{'x':padding.left, 'y':y}, {'x':width - padding.right, 'y':y}]))
            .attr("stroke-width",1).attr("stroke-dasharray", "3,8")
            .attr("fill","none")
            .attr("class", "line1");
    }

    ////// 鼠标提示 //////
    function addTooltip(){
        function formatTime(t1, t2){
            var y1 = t1, y2 = t2;
            return (y2 - y1) + "年";
        }
        var tip = d3.tip().attr('class', 'd3-tip').offset([-10, 0]).html(function(d) {
            if('name' in d){
                var name = d.name, levels = {0:"不合格", 1:"合格", 2:"称职", 3:"优秀"};
                return "<strong>" + name + "： </strong><span style='color:red'>"+ levels[d.data[1]]
                    + "</span><p style='margin-top: 10px'>" + name + "时间："+ d.data[0] +"年</p>";
            }
            var name = d[d.length - 1], lvTexts = (name=="任职") ? levelAdm : levelEdu;
            var nameText = "", timeText = "";
            if(name=="荣誉"){
                nameText = d[1];
                timeText = d[0] + "年";
            }else{
                nameText = lvTexts[lvTexts.length - d[2]];
                timeText = formatTime(d[0], d[1]);
            }
            var html = "<strong>" + name + ": </strong> <span style='color:indianred'>" + nameText
                + "</span><p style='margin-top: 10px'>" + "时长："+ timeText +"</p>"
                + "</span><p style='margin-top: 10px'>" + "地点："+ "雅安市" +"</p>";

            if(name=="任职") html += "职务：" + d[3];

            return html;
        });
        svg.call(tip);
        return tip;
    }

    addGrid();
    addAxis();
    addAxisText();
    var tip = addTooltip();
    var translate = "translate(" + (padding.left) + "," + (padding.top) + ")";

    var colors = ["#3498db", "#FFB6C1", "#7FFFAA", "#CD5C5C", "#17becf", "#567"];
    // 主图内容
    var data = [{name:"任职", type:"bar", value: [[2001, 2003, 2, "上寨村驻村干部"], [2003, 2005, 3, "乡党委组织委员, 乡综治办科员"],
        [2005, 2008, 3, "青场镇综治办主任"], [2008, 2010, 4, "水箐镇党委副书记，镇长"],
        [2010, 2015, 6, "宝兴县林业局副局长，党组成员"], [2015, 2018, 6, "雨城区政府研究室副主任，党组成员"]]},
        {name:"全日制教育", type:"bar", value: [[1986, 1991, 2, ""], [1991, 1994, 3, ""], [1994, 1997, 5, ""], [1997, 2001, 7, ""]]},
        {name:"在职教育", type:"bar", value: [[2002, 2005, 8, "在职2"]]},
        {name:"荣誉", type:"plot", value: [[2005, "先进个人", 10], [2011, "取得新职称", 10], [2013, "优秀党务工作者", 10]]},
        {name:"考核", type:"line", value: [[2001, 2], [2002, 1], [2003, 1], [2004, 3], [2005, 3], [2006, 3], [2007, 2], [2008, 1]
            , [2009, 1], [2010, 2], [2011, 3], [2012, 3], [2013, 2], [2014, 3], [2015, 3], [2016, 3], [2017, 3]]}
    ];

    function drawBaseBar(){
        data.forEach(function(item, i){
            if(item.type==="bar"){
                svg.append("g").selectAll("rect").data(item.value)
                    .enter().append("rect").attr("x", function(d){ d.push(item.name); return xScale(d[0]); })
                    .attr("y", function(d){ return yScale(d[2]); })
                    .attr("width", function(d){ return xScale(1979 + d[1] - d[0]); })
                    .attr("height", function(d){ return yScale(level - 1); })
                    .attr("transform", translate)
                    //.attr("rx", 2)
                    .attr("stroke", "#fff")
                    .attr("fill", colors[i]).attr("opacity", "0.8")
                    .on('mouseover', tip.show)
                    .on('mouseout', tip.hide);
            }else if(item.type==="plot"){
                svg.append("g").selectAll("circle").data(item.value)
                    .enter().append("circle").attr("cx", function(d){ d.push(item.name); return xScale(d[0]); })
                    .attr("cy", function(d){ return yScale(d[2]) + disY / 2; })
                    .attr("r", disY / 3)
                    .attr("tag", function(d, j){ return j; })
                    .attr("transform", translate)
                    .attr("fill", colors[i]).attr("opacity", "0.2").attr("stroke", "rgba(0, 0, 0, 0.05)")
                    .on('mouseover', tip.show)
                    .on('mouseout', tip.hide)
                    .on('mouseover.color', mouseOn)
                    .on('mouseout.color', mouseOut);
                ////// asix 提示线 //////
                svg.append("g").selectAll(".lineP").data(item.value).enter().append("path")
                    .attr("d", function(d){
                        return lineFunc([{'x':xScale(d[0]), 'y':SVGH}, {'x':xScale(d[0]), 'y':yScale(d[2]) + disY/5*4 }]) ;})
                    .attr("stroke","red")
                    .attr("transform", translate)
                    .attr("class", "lineP")
                    .attr("id", function(d, i){ return "plotL" + i; } )
                    .attr("stroke-width", 0.5).attr("stroke-dasharray", "2,2")
                    .attr("fill","none")
                    .style("display", "none");

            }else if(item.type==="line") {
                var dataset = item.value.map(function(d){
                    return {'x': xScale(d[0]), 'y': yScale(10 + d[1]), 'name':item.name, "data":d };
                });
                svg.append("g").append("path")
                    .attr("d", function(d){ cout(d); return lineFunc(dataset); })
                    .attr("stroke", colors[i])
                    .attr("transform", translate)
                    .attr("stroke-width", 1)
                    .attr("fill" ,"none")
                    .attr("class" ,"line2")
                ;

                svg.append("g").selectAll('circle').data(dataset).enter().append('circle')
                    .attr('cx', function(d) { return d.x; })
                    .attr('cy', function(d) { return d.y; })
                    .attr('r', 2.5)
                    .attr("tag", function(d, j){ return j; })
                    .attr("transform", translate)
                    .attr('fill', colors[0])
                    .on('mouseover', tip.show)
                    .on('mouseout', tip.hide)
                    .on('mouseover.color', mouseOn)
                    .on('mouseout.color', mouseOut);
                ////// asix 提示线 //////
                svg.append("g").selectAll(".lineP").data(item.value).enter().append("path")
                    .attr("d", function(d){
                        return lineFunc([{'x':xScale(d[0]), 'y':SVGH}, {'x':xScale(d[0]), 'y':yScale(10 + d[1])  }]) ;})
                    .attr("stroke","red")
                    .attr("transform", translate)
                    .attr("class", "lineP")
                    .attr("id", function(d, i){ return "lineL" + i; } )
                    .attr("stroke-width", 0.5).attr("stroke-dasharray", "2,2")
                    .attr("fill","none")
                    .style("display", "none")
                ;
            }
            function getMouseLink(obj, d){
                var name = "";
                if("name" in d)name = d.name; else name = d[d.length - 1];
                var pre = {"荣誉":"plotL", "考核":"lineL"}[name];  cout(d);
                return d3.select("#" + pre + obj.attr("tag"));
            }
            function mouseOn(d){
                var self = d3.select(this), pLine = getMouseLink(self, d);
                if("name" in d)self.attr("r", 3); else self.attr("opacity", "1");
                pLine.style("display", "");
            }
            function mouseOut(d){
                var self = d3.select(this), pLine = getMouseLink(self, d);cout(d);
                if("name" in d)self.attr("r", 2.5); else self.attr("opacity", "0.2");
                pLine.style("display", "none");
            }


        });

    }
    drawBaseBar();

    DrawLegend(svg, data.map(function(d){ return d.name; }), colors, padding.left);






}

////// Legend //////
////// svg容器、数据、颜色配置、位置左、位置上//////
function DrawLegend(svg, lg, colors, left, top){
    colors = colors || ["#3498db", "#FFB6C1", "#7FFFAA", "#CD5C5C"];
    left = left || 50;
    top = top || 5;
    var g = svg.append("g"), cacheText = {}, lgWidth = 30;
    g.selectAll("text").data(lg).enter().append("text").attr("class", "legend").text(function(d){ return d; });
    $(".legend").each(function(i, d){ cacheText[$(d).text()] = d.getBBox().width; });
    var xStart = 0, xText = {};
    g.selectAll("rect").data(lg).enter().append("rect").attr("x", function(d, i){
        var x = xStart;
        xText[d] = xStart + lgWidth + 8;
        xStart += lgWidth + cacheText[d] + 20;
        return x;
    }).attr("id", function(d, i){ return "legend" + i; })
        .attr("y", 5)
        .attr("rx", 2)
        .attr("ry", 2)
        .attr("width", lgWidth).attr("height", 20)
        .attr("fill", function(d, i){ return colors[i]; }).style("cursor", "pointer");
    g.selectAll("text").attr("x", function(d){ return xText[d]; }).attr("y", 21);


    var lg3 = g.select("#legend3").style("display", "none");
    g.append("circle").attr("cx", parseInt(lg3.attr("x")) + lgWidth / 1.5)
        .attr("cy", parseInt(lg3.attr("y")) + 10).attr("r", 7).attr("fill", lg3.attr("fill"));

    g.attr("transform", "translate(" + left + ", " + top + ")");
    // g.attr("transform", "translate(" + parseInt((width - xStart) / 2) + ", 5)");
}



////// level : 0 1 2 //////
function drawMapCity(id, level){
    if(level==undefined) level = 0;
    var src = [["大全县", "林业局局长", 102.60, 30.08, "1990"], ["汉源县", "综合办主任", 102.64, 29.36, "1993"],
        ["雨城区", "党委副书记", 103.12, 29.81, "1995"], ["宝兴县", "林业局副局长", 102.81, 30.38, "1989"],
        ["永富乡", "副乡长", 102.66, 30.56, "1987"], ["雨城区", "区政府研究室副主任", 103.04, 30.01, "2014"]];
    var colors = ["#8470FF", "#5DADE2", "#3A5FCD"];
    var symbol = ["path://M54.227,12.611c-0.338-0.336-0.736-0.505-1.196-0.505c-0.229,0-0.712,0.188-1.446,0.559  c-0.735,0.372-1.515,0.786-2.336,1.248c-0.823,0.459-1.797,0.875-2.921,1.247c-1.123,0.371-2.163,0.559-3.12,0.559  c-0.884,0-1.664-0.168-2.336-0.505c-2.229-1.044-4.168-1.823-5.814-2.337c-1.646-0.513-3.416-0.771-5.311-0.771  c-3.272,0-6.999,1.064-11.177,3.188c-0.862,0.43-1.48,0.763-1.88,1.007l-0.397-2.911c0.897-0.779,1.476-1.914,1.476-3.195  c0-2.347-1.902-4.249-4.249-4.249c-2.347,0-4.249,1.902-4.249,4.249c0,1.531,0.818,2.862,2.032,3.61l5.74,42.09  c0.171,1.253,1.243,2.162,2.474,2.162c0.112,0,0.226-0.007,0.341-0.022c1.368-0.188,2.326-1.447,2.139-2.815L19.69,38.303  c4.186-2.077,7.807-3.124,10.853-3.124c1.293,0,2.554,0.193,3.783,0.583c1.23,0.391,2.253,0.815,3.067,1.274  c0.814,0.46,1.775,0.886,2.88,1.274c1.107,0.39,2.2,0.585,3.279,0.585c2.726,0,5.991-1.027,9.796-3.08  c0.478-0.248,0.828-0.492,1.049-0.731c0.221-0.239,0.332-0.579,0.332-1.021V13.806C54.729,13.347,54.562,12.948,54.227,12.611z",
        "pin", "roundRect", "arrow", "diamond"
    ];
    var dts = [["副科级", [src[1]]], ["正科级", [src[0], src[3], src[2], src[4]]], ["副处级", [src[5]]]];
    var series = dts.map(function(item, i){ return {
        name: item[0],
        type: 'effectScatter', coordinateSystem: 'geo', zlevel: i+1,
        label: { normal: { show: true, position: 'right', formatter: '{b}', textStyle:{ fontSize:13 } } },
        symbolSize: function (val) { return i*2 + 2; },
        symbol: symbol[i],
        itemStyle: { normal: { color: colors[i] } },
        data: item[1].map(function (d) { return { name: d[0] + d[1], value: [d[2], d[3], i] }; })
    }});
    var lines = [];
    src.sort(function(a, b){ return parseInt(a[4]) - parseInt(b[4]); });
    src.forEach(function(d, i){
        if(i!==0)lines.push({
            fromName: src[i - 1][0], toName:d[0], coords:[[src[i - 1][2], src[i - 1][3]], [d[2], d[3]]]
        });
    });
    series.push({
        type: 'lines', zlevel: 10,
        symbol: ['none', 'arrow'],
        symbolSize: 10,
        lineStyle: { normal: { color: "#555", width: 1, opacity: 0.6, curveness: 0.1 } },
        data: lines
    });

    var option = {
        backgroundColor: '#fff',
        title : { text: '雅安市', left: 'center' }, tooltip : { trigger: 'item' },
        legend: {
            orient: 'vertical', top: 'top', left: 'right',
            data:dts.map(function(d){ return d[0]; }), textStyle: {color: '#000' }
        },
        geo: {
            map: '雅安', label: { emphasis: { show: true } }, zoom: 1.2, roam: true,
            itemStyle: {
                normal: { areaColor: '#eee', borderColor: '#aaa' }, emphasis: { areaColor: '#eee' }
            }
        },
        series: series
    };

    if(level==1){
        option.geo.map = "四川";
        option.geo.regions = [{
            name: '雅安市',
            itemStyle: { normal: { areaColor: '#FFE4C4', color: 'red' }
            }
        }];
    }
    if(level==2){
        option.geo.map = "china";
        option.geo.regions = [{
            name: '四川',
            itemStyle: { normal: { areaColor: '#FFE4C4', color: 'red' }}
        }];
    }

    Init3(option, id);

}



function getGraphData(dts){
    var data = {
        "categories": [
            {
                "name": "上游",
                "text": "",
            }],
        "nodes": [
            {
                "name": "公司名称A",
                "value": 1,
                "category": 4
            }],
        "links": [
            {
                "source": 0,
                "target": 1,
                "relation": 0
            }]
    };
    var index = 0, cacheC = dts.reduce(function(a, b){ if(!(b[6] in a))index++; a[b[6]] = index - 1; return a; }, {});
    var rels = ['同事', '校友', '亲属', '老乡'];
    data.categories = rels.map(function(d){ return { "name":d }; });

    // data.categories = Object.keys( cacheC).map(function(d){ return { "name":d }; });
    data.nodes = dts.map(function(d, i){
        return { "name": d[7],
            "value": i==0 ? 10 :parseInt(Math.random() * 4),
            "category": rels[parseInt(Math.random() * rels.length)]//cacheC[d[6]]
        };
    });
    data.links = [];
    var r = function(){ return parseInt(Math.random() * dts.length); };
    var cacheL = {};
    for(var i=0; i<Math.random() * 5 + 10; i++){
        var s = r(), t = r(), rel = rels[parseInt(Math.random() * rels.length)];
        if(0==t) continue;
        // 重复边检测
        if((0 + "_" + t) in cacheL){
            continue;
        }else{
            cacheL[0 + "_" + t] = 1;
        }

        data.links.push({
            "source": 0,
            "target": t,
            "relation": rel
        });
    }
    for(var i=0; i<Math.random() * 10 + 5; i++){
        var s = r(), t = r(), rel = rels[parseInt(Math.random() * rels.length)];
        if(s==t) continue;
        // 重复边检测
        if((s + "_" + t) in cacheL || (t + "_" + s) in cacheL){
            continue;
        }else{
            cacheL[s + "_" + t] = 1;
        }

        data.links.push({
            "source": s,
            "target": t,
            "relation": rel
        });
    }
    cout(cacheC);
    return data;
}

function setTable(graph){
    var body = graph.links.filter(function(d){
        return true;
    }).map(function(d){
        var styleS = ' style = "color:' + (d.source==0 ? 'red' : '#000') + '"';
        var styleT = ' style = "color:' + (d.target==0 ? 'red' : '#000') + '"';
        return "<tr>" +
            "<td"+ styleS + ">" + graph.nodes[d.source].name + "</td>" +
            "<td"+ styleT + ">" + graph.nodes[d.target].name + "</td>" +
            "<td>"+ d.relation + "</td>" +
            "<td>"+ "时间" + "</td>" +
            //"<td>"+ (2002 + parseInt(Math.random() * 15) ) + "</td>" +
        + "</tr>"; }).join("");
    $("#tbody0").html(body);
}

function drawGraph(id, data){
    var graph = data;
    var categories = graph.categories;//.map(function(d){ return {name:d.name}; });
    setTable(graph);

    graph.nodes.forEach(function (node) {
        node.itemStyle = null;
        node.symbolSize = node.value * 3 + 10;
        node.label = {
            normal: {
                show: node.symbolSize > 1
            }
        };
    });

    var option = {
        title: {
            text: '个人关系网络',
            subtext: '',
            top: 'top',
            left: 'left'
        },
        legend: [{
            orient:'vertical', right:80, top:20,
            data: categories.map(function (a) {
                return a.name;
            })
        }],
        animationDuration: 3000,
        animationEasingUpdate: 'quinticInOut',
        series: [{
            type: 'graph',
            layout: 'force',
            force: {
                repulsion: 300
            },
            edgeSymbol: ['', 'arrow'],
            edgeSymbolSize: 5,
            data: graph.nodes,
            links: graph.links,
            categories: categories,
            focusNodeAdjacency: true,
            roam: true,
            label: {
                normal: {
                    show: true,
                    position: 'top',
                }
            },
            lineStyle: {
                normal: {
                    color: 'source',
                    curveness: 0,
                    type: "solid"
                }
            },
            edgeLabel: {
                emphasis: {
                    show: true,
                    textStyle: {
                        fontSize: 12, color:'red'
                    },
                    formatter: function(p){
                        return p.data.relation;
                    }
                }
            }
        }]
    };

    Init3(option, id);
}


